package org.phpgwt.remote;

import java.util.List;
import java.util.logging.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNull;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.gwtent.serialization.client.json.JsonSerializer;

public class RemoteService {
	private static RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, GWT.getModuleBaseURL() + "phpgwt.php");
	private static Logger logger = Logger.getLogger("RemoteService");

	public static void RPC(String service, String function, RequestCallback callback, Object... parameters) {
		JSONObject call = new JSONObject();
		call.put("service", new JSONString(service));
		call.put("function", new JSONString(function));

		JSONArray callParameters = new JSONArray();
		call.put("parameters", callParameters);

		for (int i = 0; i < parameters.length; i++) {
			final Object parameter = parameters[i];

			if (parameter instanceof PHPObject) {
				callParameters.set(i, JsonSerializer.serializeObject(parameter));
			} else if (parameter != null) {
				if (parameter instanceof List || parameter.getClass().isArray()) {
					callParameters.set(i, JsonSerializer.serializeIterable((Iterable) parameter));
				} else {
					callParameters.set(i, new JSONString("" + parameter));
				}
			} else {
				callParameters.set(i, JSONNull.getInstance());
			}
		}

		String json = call.toString();
		System.out.println(json);
		String data = "data=" + URL.encodeQueryString(json);

		Request request = null;
		try {
			requestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded");
			request = requestBuilder.sendRequest(data, callback);
		} catch (RequestException e) {
			callback.onError(request, e);
		}

	}
}
